package com.lottemall.upload.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.lottemall.common.enums.ExceptionEnume;
import com.lottemall.common.exception.LtException;
import com.lottemall.upload.config.UploadProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 处理图片上传的业务逻辑类
 */
@Service
@Slf4j
@EnableConfigurationProperties(UploadProperties.class) //需要里面的图片地址和允许类型，这里加上下面就可以自动注入
public class UploadService {

    //先暂时定义允许的文件类型(本该配置一个配置类，这里先写死)
//    private static final List<String> ALLOW_IMAGE_TYPE = Arrays.asList("image/jpeg", "image/png", "image/bmp");

    @Autowired
    private UploadProperties uploadProperties;
    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    public String uploadImage(MultipartFile file) {
        try {
            //校验文件
            String contentType = file.getContentType();
            if (!uploadProperties.getAllowTypes().contains(contentType)) {
                throw new LtException(ExceptionEnume.INVALID_FILE_TYPE);
            }

            //校验文件的类容(如果输入流类容不是图片的，则这个变量就是Null,小可能是异常,其实还可以读他的宽高等信息来校验)
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null) {
                throw new LtException(ExceptionEnume.INVALID_FILE_TYPE);
            }
            //准备目标路径,并加上文件名字（这里暂时准备的是本地）
//            File dest = new File("E:\\temp\\idea-Projects\\picture_temporary\\lottemall\\upload", file.getOriginalFilename());

            //获取文件后缀名
//            String extension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");//在这个字符串最后一个点的后面截取
            //上传到FastDFS
            StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);

            //返回路径(这个会通过nginx反向代理，访问分布式文件系统)
            return uploadProperties.getBaseUrl() + storePath.getFullPath();
        } catch (IOException e) {
            //上传失败
            log.error("[文件上传]上传文件失败！", e);
            throw new LtException(ExceptionEnume.UPLOAD_FILE_ERROR);
        }
    }
}
